"""
取消订单
"""
import os
import sys
import django

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.extend([BASE_DIR, ])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finance_c2c.settings")
django.setup()
import requests
import time
import datetime
from core.tools.custom_requests import CustomRequests
from apps.czb.base import CzbApiBase
from finance_c2c.local_settings import ONLINE
from core.tools.func_utils import FuncUtils
from apps.czb.models import Orders
from django.db.models import F
from apps.user_operation.APIClient import api_client


class CzbApi(CustomRequests, CzbApiBase):
    def __init__(self):
        self.app_secret = "06baa15ad11f4a37b0711464558d89a2"
        self.key = "nanjingyinhang"

    # 获取车主邦加油站信息保存到本地
    def query_gas_info_list(self):
        base_url = "http://127.0.0.1:8002/v1/api/initGas/"
        parameters = {
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "appKey": self.key
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters)
        # response = self.post(base_url, json=parameters)
        response = self.post(base_url, data=parameters)
        return response

    # 用户登录
    def platform_login(self, tel):
        base_url = "http://127.0.0.1:8002/v1/api/login"
        parameters = {
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "appKey": self.key,
            "mobile": tel
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        response = self.post(base_url, data=parameters)
        return response

    # 订单查询
    def query_order(self, outerOrderId):
        base_url = "http://127.0.0.1:8002/v1/api/queryOrders/"
        parameters = {
            "appKey": self.key,
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "outerOrderId": outerOrderId,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        response = self.post(base_url, data=parameters)
        return response

    #  根据用户查询油站状态和油价
    def query_price_by_phone(self, gasIds, mobile, token):
        base_url = "http://127.0.0.1:8002/v1/api/queryGasByPhone/"
        parameters = {
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "appKey": self.key,
            "mobile": mobile,
            "gasIds": gasIds
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        # token = "ZXlKMGVYQWlPaUpLVjFRaUxDSmhiR2NpT2lKSVV6STFOaUo5LmV5SjFjMlZ5WDJsa0lqb3hNRFlzSW5WelpYSnVZVzFsSWpvaU1UZzJNVEl6T0RZeU16TWlMQ0psZUhBaU9qRTFPREF5TnpJMU5ETXNJbXhsWVdSbGNpSTZNVEF6TENKaVlXNXJYMk5oY21SZmJtOGlPaUlpTENKb1pXRmtaWEpmYVcxbklqb2lhSFIwY0hNNkx5OXphRzl3TG10aGJHRnBZbUZ2TG1OdmJTOW9OUzlrWldaaGRXeDBYMmhsWVdSbGNpNXdibWNpTENKMWMyVnlYMk52WkdVaU9pSWlMQ0p0YjJKcGJHVWlPaUl4T0RZeE1qTTROakl6TXlJc0ltSmhibXNpT2lJaUxDSnVZVzFsSWpwdWRXeHNMQ0pqYjIxd1lXNTVYMjVoYldVaU9pSWlmUS5nYncxMGVKaUtJOEE0MHNod3Q3X3BRTlpKaVZaT3J6eHkwNlhscEpybWlz"
        headers = {"AUTHORIZATION": token}
        response = self.post(base_url, json=parameters, headers=headers)
        print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return response

    # 获取token
    def get_token_from_mc(self, tel):
        token_key = self.get_token_key(tel)
        if not self.mc.get(token_key):
            response = self.platform_login(tel)
            result = response.get("result")
            token = result.get("token")
            return token
        else:
            token = self.mc.get(token_key)
            print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "token,mc:", token)
            return token

    # h5支付获取支付链接
    def get_pay_url(self, tel, gasId, gunNo):
        """
        :param tel: 手机号
        :param gasId: 油站
        :param gunNo: 油枪
        :return:
        """
        base_url = "https://test-open.czb365.com"
        format_str = {"base_url": base_url, "platformType": self.channelId, "platformCode": tel, "gasId": gasId,
                      "gunNo": gunNo}
        url = "{base_url}/redirection/todo/?platformType={platformType}&platformCode={platformCode}&gasId={gasId}&gunNo={gunNo}".format(
            **format_str)
        return url

    # 提交订单
    def generate_order(self, token):
        """
        :param gunNo: 抢号  70
        :param gasId: 油站id DM425228581
        :param amountGun:  用户输入价格  100
        :param priceGun: 枪价
        :param priceUnit: 下单时享有价格
        :param litre:
        :param token: 车主邦用户token
        升数 = amountGun(订单总金额) / priceGun(下单时实时枪价)
        实付 = 升数 * priceUnit（下单时享有单价）
        优惠金额 = amountGun - 实付
        :return:
        """
        gasId = "QF000011595"
        gunNo = "2"
        amountGun = "64.40"
        outerOrderId = FuncUtils().unique_value
        base_url = "http://127.0.0.1:8002/v1/api/generateOrders/"
        # parameters = {
        #     "appKey": self.key,
        #     "timeStamp": str(time.time()).replace(".", "")[:13],
        #     "gunNumber": str(gunNo),
        #     "gasId": gasId,
        #     "amountGun": str(amountGun),
        #     "outerOrderId": outerOrderId,
        #     "litre": "14.47",
        #     "priceGun": "6.91",
        #     "priceUnit": "5.93",
        # }

        parameters = {
            "appKey": self.key,
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "gunNumber": str(gunNo),
            "gasId": gasId,
            "amountGun": str(amountGun),
            "outerOrderId": outerOrderId,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "请求数据")
        headers = {"AUTHORIZATION": token}
        response = self.post(base_url, json=parameters, headers=headers)
        # response = requests.post(base_url, json=parameters, headers=headers)
        return response

    # 取消订单
    def cancel_order(self, outerOrderId, token):
        """
        :param orderId: 车主邦orderId
        :return:
        """
        base_url = "http://127.0.0.1:8002/v1/api/cancelOrders/"
        parameters = {
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "appKey": self.key,
            "outerOrderId": outerOrderId,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        headers = {"AUTHORIZATION": token}
        response = self.post(base_url, json=parameters, headers=headers)
        return response

    # 支付回告
    def order_pay(self, outerOrderId, payAmount):
        base_url = "http://127.0.0.1:8002/v1/api/payCallback/"
        parameters = {
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "appKey": self.key,
            "outerOrderId": outerOrderId,
            "payAmount": int(payAmount),
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "api_test支付接口请求参数")
        headers = {"AUTHORIZATION": token}
        response = self.post(base_url, json=parameters, headers=headers)
        return response

    # 开发票
    def insert_invoice(self, outerOrderId, user_token):
        base_url = "http://127.0.0.1:8002/v1/api/insertInvoice/"
        parameters = {
            "outerOrderId": outerOrderId,
            # "title": 0,  # 0公司 1个人
            # "buyerName": "测试有限公司",
            # "buyerTaxNo": "9161000069111150XL",
            "title": 1,  # 0公司 1个人
            "buyerName": "测试",
            "buyerEmail": "test@qq.com",
            "buyerAddressPhone": "购方地址及电话",
            "buyerBankAccount": "购方开户行及账号",
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "appKey": self.key,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "支付接口请求参数")
        headers = {"AUTHORIZATION": user_token}
        response = self.post(base_url, json=parameters, headers=headers)
        return response

    # 查询已开发票
    def queryInvoice(self, user_token):
        base_url = "http://127.0.0.1:8002/v1/api/queryInvoice/"
        parameters = {
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "appKey": self.key,
            "pageSize": 10,
            "pageIndex": 1,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "查询已开发票")
        headers = {"AUTHORIZATION": user_token}
        response = self.post(base_url, json=parameters, headers=headers)
        return response

    # 退款接口
    def order_refund(self, payAmount, outerOrderId, token):
        base_url = "http://127.0.0.1:8002/v1/api/refund/"
        parameters = {
            "appKey": self.key,
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "refundAmount": str(payAmount),
            "outerOrderId": outerOrderId,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "申请退款请求参数")
        headers = {"AUTHORIZATION": token}
        response = self.post(base_url, json=parameters, headers=headers)
        print(response, "申请退款返回参数")
        return response

    def czb_refund_callback(self, czb_order_id, **kwargs):
        order = Orders.objects.get(id=czb_order_id)
        channel = order.channel
        app_key = channel.app_key
        d = {
            "appKey": app_key,
            "orderSn": kwargs.get("orderSn"),
            "outerOrderId": kwargs.get("outerOrderId"),
            "refundAmount": kwargs.get("refundAmount"),
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "refundTradeNo": kwargs.get("refundTradeNo"),  # 退款订单号
        }
        sign = api_client.get_sign(d, channel.app_secret)
        d["sign"] = sign
        channel.balance = F("balance") + order.payment
        channel.save()
        for i in range(3):
            response = requests.post(channel.callback, json=d, verify=False)
            if response.content.decode("utf-8") == "SUCCESS":
                break
            time.sleep(5)

            # 提交订单

    def buy_equity(self, token):
        """
        :return:
        """
        outerOrderId = FuncUtils().unique_value
        base_url = "http://127.0.0.1:8002/v1/api/equity/"
        parameters = {
            "appKey": self.key,
            "timeStamp": str(time.time()).replace(".", "")[:13],
            "month": "1",
            "outerOrderId": outerOrderId,
        }
        sign = self.get_sign(parameters, self.app_secret)
        parameters["sign"] = sign
        print(parameters, "请求数据")
        headers = {"AUTHORIZATION": token}
        response = self.post(base_url, json=parameters, headers=headers)
        # response = requests.post(base_url, json=parameters, headers=headers)
        return response

    def depreciateAmount(self, token):
        base_url = "http://127.0.0.1:8002/v1/api/depreciateAmount/"
        # parameters = {
        #     "appKey": self.key,
        #     "timeStamp": str(time.time()).replace(".", "")[:13],
        #     "gasId": "my000001126",
        #     "oilNo": "92",
        #     "amountGun": "100.00",
        # }

        parameters = {
            "appKey": "nanjingyinhang",
            "timeStamp": "1589951299",
            "gasId": "my000001126",
            "oilNo": 92,
            "amountGun": "200.00"
        }
        sign = self.get_sign(parameters, self.app_secret)
        print(sign)
        parameters["sign"] = sign
        print(parameters, "请求数据")
        headers = {"AUTHORIZATION": token}
        response = self.post(base_url, json=parameters, headers=headers)
        # response = requests.post(base_url, json=parameters, headers=headers)
        return response


czb_api = CzbApi()

if __name__ == '__main__':
    token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMDYsInVzZXJuYW1lIjoiMTg2MTIzODYyMzMiLCJleHAiOjE1OTAxOTkzMTMsImxlYWRlciI6MTAzLCJiYW5rX2NhcmRfbm8iOiIiLCJoZWFkZXJfaW1nIjoiaHR0cHM6Ly9zaG9wLmthbGFpYmFvLmNvbS9oNS9kZWZhdWx0X2hlYWRlci5wbmciLCJ1c2VyX2NvZGUiOiIiLCJtb2JpbGUiOiIxODYxMjM4NjIzMyIsImJhbmsiOiIiLCJuYW1lIjoiMTg2KioqKjIzMyIsImNvbXBhbnlfbmFtZSI6Ilx1NWMwZlx1NGYxOCJ9.NLEu0MfldqGUzrDhiyuZa0JVFxaC7j7mmkMXv5shOwk"
    # gas_init_gas = czb_api.query_gas_info_list()
    # print(gas_init_gas, "初始化数据列表")
    # login_result = czb_api.platform_login("18612386233")
    # print(login_result, "登录信息")
    # gas_list = czb_api.query_price_by_phone("QF000011595", "18612386233", token)
    # print(gas_list, "加油站列表")
    order = czb_api.generate_order(token)
    print(order, "推送订单")
    query_order_response = czb_api.query_order(order.get("result").get("outerOrderId"))
    print(query_order_response, "查询订单")
    # depreciate_result = czb_api.depreciateAmount(token)
    # print(depreciate_result, "直降金额")
    outerOrderId = order.get("result").get("outerOrderId")
    amountPay = int(order.get("result").get("amountPay") * 100)
    order_pay_result = czb_api.order_pay(outerOrderId, amountPay)
    print(order_pay_result, "支付回告接口")

    # cancel_order_response = czb_api.cancel_order(order.get("result").get("outerOrderId"), token)
    # print(cancel_order_response)
    refund_result = czb_api.order_refund(amountPay, outerOrderId, token)
    print(refund_result, "api退款返回数据")
    # a = czb_api.order_refund("CZBH153690123608533", "8582", "20011517453307915041", token)
    # r = {
    #     "app_key": "ss",
    #     "orderSn": "CZBH662634484991214",
    #     "outerOrderId": "20011611502283218564",
    #     "refundAmount": 8582,
    #     "refundTradeNo": "fdsfdsfdsfsd",
    # }
    # a = czb_api.czb_refund_callback(390, **r)
    # a = czb_api.buy_equity(token)
    # outerOrderId = a.get("result").get("outerOrderId")
    # a = czb_api.order_pay(outerOrderId, "1990")
    # a = czb_api.depreciateAmount(token)
    # print(a)
    # invoice_response = czb_api.insert_invoice(order.get("result").get("outerOrderId"), token)
    # print(invoice_response)
    # query_invoice_response = czb_api.queryInvoice(token)
    # print(query_invoice_response)
